package com.wans.guli.order.web;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wans.guli.order.service.OrderService;
import com.wans.guli.order.vo.MemberVO;
import com.wans.guli.order.vo.OrderConfirmVo;
import com.wans.guli.order.vo.SubmitOrderResponseVo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@Controller
@Slf4j
public class WebViewController {

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    // 订单确认页
    @GetMapping(value = {"/", "index.html", "/toTrade"})
    @SneakyThrows
    public String toTrade(Model model, HttpSession session) {
        //TODO 幂等处理 - 设置令牌
        // 获取订单确认数据
        OrderConfirmVo orderConfirm = orderService.getOrderConfirmData();

        model.addAttribute("confirmOrderData", orderConfirm);

        // 获取用户信息
        String loginMember = (String) session.getAttribute("loginMember");
        if (loginMember == null) {
            return "redirect:http://auth.gumall.com/login.html";
        }

        MemberVO memberVO = objectMapper.readValue(loginMember, MemberVO.class);
        model.addAttribute("loginMember", memberVO);

        // 获取订单令牌
        String orderId = getOrderToken(memberVO.getId());
        model.addAttribute("orderId", orderId);

        return "confirm";
    }


    @GetMapping(value = {"toPayOrder", "createOrder"})
    @SneakyThrows
    public String createOrder(@RequestParam("addressId") Long addressId, Model model, HttpSession session) {
        // 获取用户信息
        String loginMember = (String) session.getAttribute("loginMember");
        if (loginMember == null) {
            return "redirect:http://auth.gumall.com/login.html";
        }
        // 获取用户信息
        MemberVO memberVO = objectMapper.readValue(loginMember, MemberVO.class);
        model.addAttribute("loginMember", memberVO);

        // 获取订单令牌
        String orderId = getOrderToken(memberVO.getId());
        // 创建订单
        SubmitOrderResponseVo submitOrderResponse = orderService.submitOrder(orderId, addressId);
        log.info("订单响应数据：{}", submitOrderResponse);
        // 订单响应数据
        model.addAttribute("submitOrderResp", submitOrderResponse);
        log.info("属性设置成功：{}", "submitOrderResp");

        return "pay";
    }



    /**
     * 使订单唯一id作为令牌
     *
     * @param id 用户id
     * @return 订单唯一id
     */
    private String getOrderToken(Long id) {
        // 订单唯一id
        String orderId = IdWorker.getTimeId();
//        String orderId = System.currentTimeMillis() + UUID.randomUUID().toString().replace("-", "");
        // 是否设置成功
        Boolean exist = stringRedisTemplate.opsForValue().setIfAbsent("token:order:id:" + id, orderId);
        if (Boolean.FALSE.equals(exist)) {
            // 设置失败 已存在
            return stringRedisTemplate.opsForValue().get("token:order:id:" + id);
        }

        // 是否设置成功 - 直接返回
        return orderId;
    }

    public static void main(String[] args) {
        // milliseconds 1000 关闭 close
        System.out.println(TimeUnit.MINUTES.toMillis(30));
    }

}
